import os

import pymysql
from dotenv import load_dotenv
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

pymysql.install_as_MySQLdb()
load_dotenv()
Base = declarative_base()

# ------------------------
# MySQL 基础配置
# ------------------------
MYSQL_DEFAULTS = {
    'MySQL_USERNAME': '',
    'MySQL_PASSWORD': '',
    'MySQL_HOST': 'localhost',
    'MySQL_PORT': '3306',
    'MySQL_DATABASE': '',
    'MySQL_CHARSET': 'utf8mb4',
    'SQLALCHEMY_DATABASE_URI_SCHEME': 'mysql+pymysql',
    'SQLALCHEMY_POOL_SIZE': 20,
    'SQLALCHEMY_MAX_OVERFLOW': 10,
    'SQLALCHEMY_POOL_RECYCLE': 3600,
    'SQLALCHEMY_POOL_PRE_PING': 'True',
    'SQLALCHEMY_ECHO': 'False',
    'CONSOLE_API_URL': '',
    'CHECK_UPDATE_URL': '',
    'DEPLOY_ENV': 'PRODUCTION',
    'SENTRY_TRACES_SAMPLE_RATE': 1.0,
    'SENTRY_PROFILES_SAMPLE_RATE': 1.0,
    'CELERY_BACKEND': 'database_service',
    'LOG_LEVEL': 'INFO',
    'LOG_FILE': '',
    'LOG_FORMAT': '%(asctime)s.%(msecs)03d %(levelname)s [%(threadName)s] [%(filename)s:%(lineno)d] - %(message)s',
    'LOG_DATEFORMAT': '%Y-%m-%d %H:%M:%S',
}

def get_mysql_env(key):
    return os.environ.get(key, MYSQL_DEFAULTS.get(key))

class MySQLConfig:
    """
    创建 MySQL 连接
    """

    @staticmethod
    def get_redis_client():
        SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{get_mysql_env('MySQL_USER')}:{get_mysql_env('MySQL_PASSWORD')}@" \
                              f"{get_mysql_env('MySQL_HOST')}:{get_mysql_env('MySQL_PORT')}/" \
                              f"{get_mysql_env('MySQL_NAME')}?charset={get_mysql_env('MySQL_CHARSET')}"

        engine = create_engine(SQLALCHEMY_DATABASE_URI, echo=False)
        SessionLocal = sessionmaker(
            bind=engine,
            autocommit=False,
            autoflush=False,
            expire_on_commit=False
        )

        return SessionLocal()
